<template>
  <div class="file-container" id="uniqueUploadButton">
    <el-button type="primary" class="browse-file" :icon="icon" @click="importClick" size="small">{{btnText}}</el-button>
  </div>
</template>
<script>
import XLSX from 'xlsx'
export default {
  name: 'ExcelImport',
  props: {
    btnText: {type:String,default:'上传'},
    icon: {type:String,default:null},
  },
  data() {
    return {
      arr: []
    }
  },
  methods: {
    importClick() {
      this.createUploadEle();
      document.getElementById('sUploadBtn').click();
    },
    createUploadEle() {
      let div = document.getElementById('uniqueUploadButton');
      if (div.getElementsByTagName('form')[0] != undefined) {
        div.removeChild(div.getElementsByTagName('form')[0]);
      }
      let form = document.createElement('form');
      form.id = 'uniqueUploadForm';
      form.enctype = 'multipart/form-data';
      form.width = 0;
      form.height = 0;
      form.setAttribute('style', 'display:none');
      let input = document.createElement('input');
      input.id = 'sUploadBtn';
      input.type = 'file';
      input.width = '0';
      input.height = '0';
      input.accept = this.accept;
      input.multiple = this.multiple;
      input.setAttribute('style', 'display:none');
      form.appendChild(input);
      div.appendChild(form);
      document.getElementById('sUploadBtn').onclick = this.clickFileInput.bind(this);
    },
    clickFileInput() {
      let inputHtml = document.getElementById('sUploadBtn');
      inputHtml.onchange = this.importFile.bind(this);
    },
    importFile() {
      let vueSelf = this;
      let promise = new Promise((resolve, reject) => {
        // 导入
        // FileReader共有4种读取方法：
        // 1.readAsArrayBuffer(file) ：将文件读取为ArrayBuffer。
        // 2.readAsBinaryString(file) ：将文件读取为二进制字符串
        // 3.readAsDataURL(file) ：将文件读取为Data URL
        // 4.readAsText(file, [encoding]) ：将文件读取为文本，encoding缺省值为'UTF-8'
        let wb; // 读取完成的数据
        let rABS = false;// 是否将文件读取为二进制字符串
        let obj = document.getElementById('sUploadBtn');
        if (!obj.files) {
          return
        }
        let f = obj.files[0];
        let reader = new FileReader();
        if (f == undefined) {
          return;
        }
        if (rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }
        reader.onload = function (e) {
          let data = e.target.result;
          if (rABS) {
            wb = XLSX.read(btoa(vueSelf.fixData(data)), { // 手动转化
              type: 'base64'
            })
          } else {
            wb = XLSX.read(data, {
              type: 'binary'
            })
          }
          // wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
          // wb.Sheets[Sheet名]获取第一个Sheet的数据
          this.arr = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          // console.log(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])))
          // console.log(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]))
          // return XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
          vueSelf.$emit('on-load', this.arr);
          resolve(this.arr);
        };
        reader.onerror = function (e) {
          reject(this.arr)
        }
      });
      return promise;
    },
    fixData(data) {
      let o = '';
      let l = 0;
      let w = 10240;
      for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
      return o
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.file-container {
  position: relative;
  .file-select {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
  }
}
</style>
